package com.weather.androidweather.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.weather.androidweather.R;
import java.util.ArrayList;
import java.util.List;

public class CityListAdapter extends ArrayAdapter<String> {
    private List<String> originalCities;
    private List<String> filteredCities;
    private Context context;

    public CityListAdapter(Context context, List<String> cities) {
        super(context, R.layout.item_city, cities);
        this.context = context;
        this.originalCities = new ArrayList<>(cities);
        this.filteredCities = new ArrayList<>(cities);
    }

    @Override
    public int getCount() {
        return filteredCities.size();
    }

    @Nullable
    @Override
    public String getItem(int position) {
        return filteredCities.get(position);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_city, parent, false);
        }

        TextView cityName = convertView.findViewById(R.id.cityName);
        cityName.setText(filteredCities.get(position));

        return convertView;
    }

    public void updateCities(List<String> cities) {
        this.originalCities = new ArrayList<>(cities);
        this.filteredCities = new ArrayList<>(cities);
        notifyDataSetChanged();
    }

    public void filter(String query) {
        filteredCities.clear();
        if (query == null || query.isEmpty()) {
            filteredCities.addAll(originalCities);
        } else {
            query = query.toLowerCase().trim();
            for (String city : originalCities) {
                if (city.toLowerCase().contains(query)) {
                    filteredCities.add(city);
                }
            }
        }
        notifyDataSetChanged();
    }
} 